<?php
/**
 * Created by PhpStorm.
 * User: happy
 * Date: 17/8/26
 * Time: 上午7:25
 */
//新版swoole ,尝试多线程来快上传图片的功能,也为以后异步化进行测试
//运行命令 :php index.php swoole start_socket  > log/swoole.log 2>&1 &
//启动swoole socket用于处理socket请求和web socket请求
//$serv = new swoole_server('0.0.0.0', 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);

class swoole4Control extends  Control{

    private  $server;
    //php index.php swoole4 start_http_server
    public  function  start_http_server(){
        $server=$http = new swoole_http_server("0.0.0.0", 10006);
        echo 'server start on 10006';
        $server->set(array(
            'worker_num' => 2,
            'task_worker_num' => 4,
        ));

        Swoole\Runtime::enableCoroutine();//允许携程
        $this->server=$server;

        $server->on('request', function ($request, $response) {
            //swoole 访问两次的问题
            if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {
                return $response->end();
            }

           // var_dump($request->get, $request->post);
            //$main='未找到对应的函数!';
            //$_GET=$request->get;
            //$_POST=$request->post;
            $this->swoole_run($request,$response);
        });

        $server->on('WorkerStart', function($server, $workerId) {
            echo chr(10).'worker start:'.$workerId;
           //此数组中的文件表示进程启动前就加载了，所以无法reload
            global $argv;
            if($workerId >= $server->setting['worker_num']) {
                swoole_set_process_name("php {$argv[0]}: task_worker");
            } else {
                swoole_set_process_name("php {$argv[0]}: worker");
            }
        });

        $server->on('Receive', function(swoole_server $server_param, $fd, $from_id, $data) {
            echo "接收数据" . $data . "\n";
            $data = trim($data);
           // $task_id = $server_param->task($data, 0);
           // $server_param->send($fd, "分发任务，任务id为$task_id\n");
        });

        $server->on('Task', function (swoole_server $server_param, $task_id, $from_id, $data) {
            echo "Tasker进程接收到数据";
            echo "#{$server_param->worker_id}\tonTask: [PID={$server_param->worker_pid}]: task_id=$task_id, data_len=".strlen($data).".".PHP_EOL;
            $server_param->finish($data);
        });

        $server->on('Finish', function (swoole_server $server_param, $task_id, $data) {
            echo "Task#$task_id finished, data_len=".strlen($data).PHP_EOL;
        });

        $server->start();
    }

        //启动run
    public  function  swoole_run($request,$response){
        //进行路由映射
        /*
         *  list($controller, $action) = explode('/', trim($request->server['request_uri'], '/'));
    //根据 $controller, $action 映射到不同的控制器类和方法
    (new $contoller)->$action($request, $response);*/

        $response->header("Content-Type", "text/html; charset=utf-8");
       // $this->swoole_run();
       // (new $contoller)->$action($request, $response);
           $GET=$request->get;
           $POST=$request->post;
        if($GET['reload']){
            $this->server->reload();
            $response->end('重启完成');
        }
        if($GET['image_task']){
            $task_id = $this->server->task($data, 0);

            $response->end('重启完成');
            // $server_param->send($fd, "分发任务，任务id为$task_id\n");
        }


        $act= $GET['act'] ? strtolower($GET['act']) : ($POST['act'] ? strtolower($POST['act']) : null);
        $op = $GET['op'] ? strtolower($GET['op']) : ($POST['op'] ? strtolower($POST['op']) : null);

        $act = $act ?  $act : 'swoole_index';
        $op=$op? $op : 'index';

        $act_file =BASE_PATH.'/control/'.$act.'.php';
        $class_name = $act.'Control';

            if (!class_exists($class_name,false)){
                if(file_exists($act_file)){
                    include($act_file);
                }
                else{
                    $response->end("Base Error: $act_file access file isn't exists!");
                }
            }
            if (class_exists($class_name,false)){
                $main = new $class_name();
                $function = $op;
                //定义act和op
                if (method_exists($main,$function)){
                    $main->$function($request,$response);
                }else {
                    $error = "Base Error: function $function not in $class_name!";
                    $response->end($error);
                }
            }
            else {
                $error = "Base Error: class $class_name isn't exists!";
                $response->end($error);
            }
    }
    //测试
    public  function  onStart($server){
        echo "start swoole server".chr(10);

        //启动rabbitmq连接
       // $config=c('rabbitmq'); //使用配置信息链接rabbitmq
       // plugin('rabbitmq')->rabbiConfig=$config;
       // plugin('rabbitmq')->connect($config);


    }
    public  function  onConnect($server,$fd,$from_id){
        $server->send($fd,'connect_ok'.$fd);
    }
    //直接发送数据
    public  function  onReceive(swoole_server $server,$fd,$from_id,$data){
       // var_dump($data);
        //由处理程序决定做什么操作，这个程序就是放入队列就可以了
       // plugin('rabbitmq')->send_message($data);
       // echo 'get message from client '.$fd.' '.$data;
       if(strstr($data,'order_msg')){ //如果发送短信,微信放到专门的队列中
           $config=c('rabbitmq_msg'); //使用配置信息链接rabbitmq
       }
       else if(strstr($data,'timer_msg')){
           $config=c('rabbitmq_timer'); //定时器消息
       }
        else{//放到通用队列中
            $config=c('rabbitmq'); //使用配置信息链接rabbitmq
        }

        plugin('rabbitmq')->rabbiConfig=$config;
        plugin('rabbitmq')->connect($config);
        //应该根据消息的不通放入不同的队列;
        //一个是消息通知队列,==>优先级比较高,需要尽快处理的队列,
        //一个是操作队列;====>优先级比较低,可以延后处理的队列

        plugin('rabbitmq')->send_message($data);
        plugin('rabbitmq')->close();//发送完成就可以关闭了
        echo 'receive';
        //echo $data.chr(10);
       // $server->send($fd,'receive msg and send to rabbitmq !');

    }
    //当连接关闭时操作
    public function  onClose($server,$fd,$from_id){
        /*
        $e = error_get_last();
        $error_msg=var_export($e,true);
        //15324168276 1683640  array('user'=>'','service'=>'')
        $arr=array(
            'user'=>'吕拼搏',
            'service'=>date('Y-m-d H:i:s').' swoole worker进程退出'.$error_msg
        );
        Model('util')->send_short_msg('15324168276','1683640',$arr); //通过接口发送短信

        echo 'client '.$fd.' close connection';
        */
       // echo 'client '.$fd.' close connection';
    }

}